package com.xinfu.newproject.model.person;

import com.xinfu.newproject.apiservice.JsNetworkService;
import com.xinfu.newproject.bean.person.bean.PersonBean;
import com.xinfu.newproject.bean.person.body.PersonBody;
import com.xinfu.newproject.callback.MyCallBack;
import com.xinfu.newproject.model.IModel;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class PersonModel implements IModel.IPersonModel {

    @Override
    public void upPerson(PersonBody personBody, MyCallBack<PersonBean> callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", personBody.getUserId());
        if (personBody.getAvatar() != null) {
            map.put("avatar", personBody.getAvatar());
        } /*if (personBody.getPhone() != null){
            map.put("phone",personBody.getPhone());
        }*/
        if (personBody.getProjectId() != null) {
            map.put("projectId", personBody.getProjectId());
        }
        if (personBody.getRealname() != null) {
            map.put("username", personBody.getRealname());
        }
        if (personBody.getTenantId() != null) {
            map.put("tenantId", personBody.getTenantId());
        }
        if (personBody.getSex() != null) {
            map.put("sex", personBody.getSex());
        }

        JsNetworkService.getInstance().getIJsNetworkService()
                .updateUserInfo(personBody.getHeader(), map)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PersonBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Disposable mDisposable; //用于Activity销毁时停止执行
                        mDisposable = d;
                        callBack.onDispose(mDisposable);
                    }

                    @Override
                    public void onNext(@NonNull PersonBean personBean) {

                        callBack.onSuccess(personBean);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        callBack.onError("Server Error", "网络异常，请稍后再试");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
